package com.person.controller;

import com.person.common.R;

import com.person.pojo.Emp;
import com.person.pojo.PageBean;
import com.person.service.EmpService;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.events.Event;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmpController {
    @Autowired
    private EmpService empService;


    //登录
    @PostMapping("/login")
    public R<Object> login(HttpServletRequest request, @RequestBody Emp employee){
        log.info("登录用户名和密码：{}",employee);

        //获取密码进行加密,并传入对象中
        employee.setPassword(
                DigestUtils.md5DigestAsHex(employee.getPassword().getBytes())
        );

        //根据前端传来的用户名查询数据库
        Emp emp = empService.login(employee);
        log.info("查询到的用户{}",emp);
        //没有查询到返回登录失败
        if (emp == null){
            return R.error("登录失败,用户名不存在");
        }

        //查看员工状态，如果被禁用，返回该员工已被禁用
        if ((emp.getStatus())==0) {
            return R.error("该用户已被禁用");
        }

        //登录成功
        //将id存入session，返回登录成功
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);

    }

    //退出登录
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        //清除session
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    //添加员工
    @PostMapping
    public R<Object> addEmp(HttpServletRequest request,@RequestBody Emp emp){
        log.info("添加员工：{}",emp.toString());
        empService.addEmp(request,emp);

        return R.success("添加成功");
    }

    //分页展示
    @GetMapping("page")
    public R<PageBean> page(@RequestParam(defaultValue = "1") Integer page,
                    @RequestParam(defaultValue = "10") Integer pageSize,String name){
        log.info("分页查询：{},{},{}",page,pageSize,name);
        PageBean pageBean = empService.page(page,pageSize,name);

        return R.success(pageBean);

    }

    //更改状态
    @PutMapping()
    public R<String> changeStatus(HttpServletRequest request,@RequestBody Emp emp){
        empService.updateById(request,emp);
        return R.success("更改成功");
    }

    //修改员工信息
    @GetMapping("/{id}")
    public R<Emp> getId(@PathVariable long id){
        Emp emp=empService.byId(id);
        return R.success(emp);
    }
}
